<template>
  <div class="min-h-screen " style="background-color: #f5f5f5;">
    <Top />
    <section class="bg-white flex items-center" style="height: 12vh;">
      <div class="container mx-auto px-6 w-full">
        <h2 class="text-3xl md:text-4xl font-bold" style="color:#0b2e4e;">Basic Information</h2>
      </div>
			
    </section>
		<div class="bg-white  rounded-lg p-6 ">
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8 bg-white max-w-7xl mx-auto">
        <div>
          <label class="block text-gray-700 mb-2">Country<span class="text-red-500">*</span></label>
          <el-select  
            filterable
            v-model="form.country" 
            placeholder="Please select a country" 
            class="w-full" 
            :loading="loading.areas"
            :disabled="loading.areas"
          >
            <el-option v-for="c in countries" :key="c.id" :label="c.name" :value="c.id" />
          </el-select>
          <div v-if="formErrors.country" class="text-red-500 text-sm mt-1">{{ formErrors.country }}</div>
        </div>
        <div>
          <label class="block text-gray-700 mb-2">Time Range<span class="text-red-500">*</span></label>
          <div class="flex items-center space-x-2">
            <el-date-picker
              v-model="form.startDate"
              type="date"
              value-format="YYYY/MM/DD"
              format="YYYY/MM/DD"
              placeholder="Start Date"
              class="w-full"
            />
            <span class="text-gray-500">-</span>
            <el-date-picker
              v-model="form.endDate"
              type="date"
              value-format="YYYY/MM/DD"
              format="YYYY/MM/DD"
              placeholder="End Date"
              class="w-full"
            />
          </div>
          <div v-if="formErrors.startDate || formErrors.endDate" class="text-red-500 text-sm mt-1">
            {{ formErrors.startDate || formErrors.endDate }}
          </div>
        </div>
        <div>
          <label class="block text-gray-700 mb-2">Contact Email<span class="text-red-500">*</span></label>
          <el-input v-model="form.contactEmail" placeholder="Contact Email" class="w-full" />
          <div v-if="formErrors.contactEmail" class="text-red-500 text-sm mt-1">{{ formErrors.contactEmail }}</div>
        </div>
        <div>
          <label class="block text-gray-700 mb-2">Enterprise Name<span class="text-red-500">*</span></label>
          <el-input v-model="form.enterpriseName" placeholder="Enterprise Name" class="w-full" />
          <div v-if="formErrors.enterpriseName" class="text-red-500 text-sm mt-1">{{ formErrors.enterpriseName }}</div>
        </div>
        <div>
          <label class="block text-gray-700 mb-2">Contact Information</label>
          <el-input v-model="form.contactInformation" placeholder="Contact Information" class="w-full" />
          <div v-if="formErrors.contactInformation" class="text-red-500 text-sm mt-1">{{ formErrors.contactInformation }}</div>
        </div>
      
        </div>
      </div>

    <div class="max-w-7xl mx-auto px-6 py-10">
      <!-- 基本信息表单 -->
   

      <!-- 行业列表 -->
      <div v-if="loading.industries" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-8">
        <!-- 骨架屏加载状态 -->
        <div v-for="i in 8" :key="i" class="rounded-lg overflow-hidden shadow-sm">
          <div class="h-40 bg-gray-200 animate-pulse"></div>
          <div class="text-center py-4 bg-white border-t border-gray-200">
            <div class="h-6 bg-gray-200 animate-pulse rounded mx-4"></div>
          </div>
        </div>
      </div>
      <div v-else class="flex flex-wrap gap-8 justify-center">
        <div v-for="item in industries" :key="item.code" 
             :class="[
               'rounded-lg overflow-hidden shadow-sm cursor-pointer hover:shadow-md transition flex-shrink-0',
               item.active ? 'border-4 border-[#0066a1]' : 'border border-gray-200'
             ]"
             style="width: 200px;"
             @click="toggleIndustry(item)">
          <div class="h-40 bg-gray-100">
            <img v-if="item.image" :src="item.image" alt="" class="w-full h-full object-cover" />
            <div v-else class="w-full h-full bg-gray-200"></div>
          </div>
          <div :class="[
              'text-center py-4 text-lg font-semibold border-t whitespace-nowrap',
              item.active ? 'bg-blue-700 text-white border-blue-700' : 'bg-white text-gray-800 border-gray-200'
            ]">
            {{ item.name }}
          </div>
        </div>
      </div>

      <!-- 生产工艺与排放计算表单 -->

    </div>
    <div style="background-color: #fff;width: 100vw;display: flex;align-self: center;justify-content: center;">
      <div class="mt-12">
        <div v-if="selectedIndustry" class="bg-white border rounded-lg p-6">
          <h3 class="text-xl font-semibold mb-6" style="color:#0b2e4e;">Carbon Emissions - {{ selectedIndustry.name }}</h3>

          <!-- 生产工艺选择 -->
          <!-- <div class="flex items-center space-x-6 mb-6">
            <span class="text-gray-800 font-medium" style="font-size:30px;">Production process:</span>
            <label class="inline-flex items-center space-x-2 cursor-pointer text-lg">
              <input type="radio" class="form-radio w-6 h-6" value="long" v-model="processType" />
              <span>Long process</span>
            </label>
            <label class="inline-flex items-center space-x-2 cursor-pointer text-lg ml-10">
              <input type="radio" class="form-radio w-6 h-6" value="short" v-model="processType" />
              <span>Short process</span>
            </label>
          </div> -->

          <div v-if="loading.formParams" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            <!-- 表单参数加载骨架屏 -->
            <div v-for="i in 6" :key="i" class=" p-4 rounded-lg">
              <div class="h-4 bg-gray-200 animate-pulse rounded mb-2"></div>
              <div class="flex">
                <div class="flex-1 h-10 bg-gray-200 animate-pulse rounded-l"></div>
                <div class="w-20 h-10 bg-gray-100 animate-pulse rounded-r"></div>
              </div>
            </div>
          </div>
          <div v-else>
            <!-- 节点字段（条件选择器） -->
            <div v-if="visibleNodeFields.length > 0" class="mb-8">
              <div v-for="nodeParam in visibleNodeFields" :key="nodeParam.paramKey" class="mb-6">
                <label class="block text-sm text-gray-700 mb-2">
                  {{ nodeParam.paramLabel }} 
                  <span class="text-red-500">*</span>
                </label>
                <div class="space-y-2">
                  <label v-for="option in parseParamJson(nodeParam.paramJson)" :key="option.value" 
                         class="inline-flex items-center space-x-2 cursor-pointer">
                    <input 
                      type="radio" 
                      :name="nodeParam.paramKey"
                      :value="option.value" 
                      :checked="dynamicForm[nodeParam.paramKey] === option.value"
                      @change="onNodeFieldChange(nodeParam.paramKey, option.value)"
                      class="form-radio w-4 h-4" 
                      style="margin-left: 10px;"
                    />
                    <span>{{ option.label }}</span>
                  </label>
                </div>
                <div v-if="formErrors[nodeParam.paramKey]" class="text-red-500 text-sm mt-1">{{ formErrors[nodeParam.paramKey] }}</div>
              </div>
            </div>

            <!-- 当前流程的表单字段 -->
            
            <div v-if="currentFormFields.length > 0" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
              <!-- ⚠️ 统一的 huilv 字段渲染（使用动态 label） -->   
              <div class="p-4 rounded-lg">
                <label class="block text-sm text-gray-700 mb-2">
                  {{ huilvLabel }}
                  <span class="text-red-500">*</span>
                </label>
                <div class="flex bg-gray-50" style="background-color: #f2f3f5">
                  <input 
                    v-model="dynamicForm.huilv" 
                    type="number" 
                    step="any" 
                    class="flex-1 border rounded-l bg-white px-3 py-2 placeholder:text-xs" 
                    :class="formErrors.huilv ? 'border-red-500' : ''"
                    :placeholder="huilvPlaceholder" 
                  />
                   <div class="px-3 py-2 border border-l-0 rounded-r text-gray-500 flex items-center justify-between relative currency-dropdown-container cursor-pointer" @click="toggleCurrencyDropdown">
                     <span>{{ displayCurrencySymbol }}</span>
                     <svg class="w-3 h-3 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                       <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="m19 9-7 7-7-7"></path>
                     </svg>
                     <div v-if="showCurrencyDropdown" class="absolute top-full left-0 mt-1 bg-white border border-gray-300 rounded shadow-lg z-50 max-h-40 overflow-y-auto w-20">
                       <div 
                         v-for="currency in availableCurrencies" 
                         :key="currency.currencyCode"
                         class="px-3 py-2 hover:bg-gray-100 cursor-pointer text-sm"
                         @click="selectCurrency(currency.currencyCode)"
                       >
                         {{ currency.symbol }}
                       </div>
                     </div>
                   </div>
                </div>
                <div v-if="formErrors.huilv" class="text-red-500 text-sm mt-1">{{ formErrors.huilv }}</div>
              </div>

              <!-- ⚠️ 动态字段循环（排除 huilv） -->
              <div v-for="param in currentFormFieldsWithoutHuilv" :key="param.flowId + '_' + param.paramKey">
                 <!-- 输入框类型 -->
                 <div v-if="param.paramType === '1'" class="p-4 rounded-lg">
                  <label class="block text-sm text-gray-700 mb-2">
                    {{ param.paramLabel }} 
                    <span v-if="param.isNode === 'Y'" class="text-red-500">*</span>
                  </label>
                  <div class="flex bg-gray-50" style="background-color: #f2f3f5">
                    <input 
                      v-model="dynamicForm[param.paramKey]" 
                      type="number" 
                      step="any" 
                      class="flex-1 bg-white border rounded-l px-3 py-2 placeholder:text-xs" 
                      :class="formErrors[param.paramKey] ? 'border-red-500' : ''"
                      :placeholder="`Please enter ${formatPlaceholderText(param.paramLabel)}`"
                    />
                    <div class="px-3 py-2 border border-l-0 rounded-r text-gray-500">
                      {{ getUnitByParamKey(param.paramKey) }}
                    </div>
                  </div>
                  <div v-if="formErrors[param.paramKey]" class="text-red-500 text-sm mt-1">{{ formErrors[param.paramKey] }}</div>
                </div>

                <!-- 单选框类型 -->
                <div v-else-if="param.paramType === '2'" class="p-4 rounded-lg">
                  <label class="block text-sm text-gray-700 mb-2">
                    {{ param.paramLabel }} 
                    <span v-if="param.isNode === 'Y'" class="text-red-500">*</span>
                  </label>
                  <div class="space-y-2">
                    <label v-for="option in parseParamJson(param.paramJson)" :key="option.value" 
                           class="inline-flex items-center space-x-2 cursor-pointer">
                      <input 
                        type="radio" 
                        :name="param.paramKey"
                        :value="option.value" 
                        v-model="dynamicForm[param.paramKey]" 
                        class="form-radio w-4 h-4" 
                        style="margin-left: 10px;"
                      />
                      <span>{{ option.label }}</span>
                    </label>
                  </div>
                  <div v-if="formErrors[param.paramKey]" class="text-red-500 text-sm mt-1">{{ formErrors[param.paramKey] }}</div>
                </div>
              </div>
            </div>
          </div>

          <!-- <p class="text-gray-600 text-sm mt-6">
            Calculation formula: ((sintering/pellet × 1.6 + blast furnace + converter + rolling) − 1.7541) × export volume × carbon price × exchange rate − carbon cost paid for the commodity domestically
          </p> -->
          <!-- <p class="text-gray-500 text-xs mt-2">Data source: European Commission Implementing Regulation 2021/447 of March 12, 2021: Revised baseline values for free quota allocation for 2021-2025</p> -->

          <div class="mt-6">
            <label class="inline-flex items-start space-x-2 text-sm text-gray-600 cursor-pointer">
              <input type="checkbox" v-model="agree" class="mt-1" />
              <span>I am aware of the Disclaimer that informs customers of data security issues and related legal issues when filling out data</span>
            </label>
            <div v-if="disclaimerError" class="text-red-500 text-sm mt-1">{{ disclaimerError }}</div>
          </div>

          <div class="mt-6">
            <button 
              @click="handleCalculate" 
              class="inline-flex items-center px-5 py-3 text-white rounded cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed" 
              style="background-color:#0066a1;"
            >
              <div v-if="loading.calculating" class="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>
             Carbon tariff calculation
              <svg v-if="!loading.calculating" class="w-5 h-5 ml-2" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" d="M9 5l7 7-7 7"/>
              </svg>
            </button>
          </div>
        </div>

        <div v-else class="bg-white border rounded-lg p-6 text-center text-gray-500">
          Please select an industry to view the calculation form
        </div>

        <!-- <div class="mt-6 border rounded p-3 text-sm bg-white" >
          <span class="mr-4" style="color: red;">Estimated carbon tariff amount:¥9.29
						You have exceeded the estimated amount of carbon tariff exemption</span>
            <a class="text-blue-600 underline" href="#" @click.prevent>Please click here to view response suggestions</a>
        </div> -->
      </div>
     </div>
    <Bottom />
  </div>
</template>

<script setup>
import { computed, onMounted, ref, watch } from 'vue'
import { areaApi, countApi } from '~/public/utils/api'
import { useLoginDialog } from '~/composables/useLoginDialog'

definePageMeta({ layout: false })

const form = ref({
  country: '',
  startDate: '',
  endDate: '',
  enterpriseName: '',
  contactInformation: '',
  contactEmail: ''
})

// 国家选项
const countries = ref([])

// 货币符号
const currencySymbols = ref({})

// 汇率数据
const exchangeRates = ref({})

// 可选择的货币列表
const availableCurrencies = computed(() => {
  const currencies = []
  Object.keys(currencySymbols.value).forEach(currencyCode => {
    currencies.push({
      currencyCode,
      symbol: currencySymbols.value[currencyCode]
    })
  })
  return currencies
})

// 显示当前选中的货币符号
const displayCurrencySymbol = computed(() => {
  if (!dynamicForm.value.currencyCodeTarget) {
    return 'Currency'
  }
  // 直接从currencySymbols对象中获取symbol
  return currencySymbols.value[dynamicForm.value.currencyCodeTarget] || 'Currency'
})

// 下拉菜单显示状态
const showCurrencyDropdown = ref(false)

// 切换下拉菜单
const toggleCurrencyDropdown = () => {
  showCurrencyDropdown.value = !showCurrencyDropdown.value
}

// 选择货币
const selectCurrency = (currencyCode) => {
  dynamicForm.value.currencyCodeTarget = currencyCode
  showCurrencyDropdown.value = false
  fillExchangeRate()
}

// 获取汇率数据
const fetchExchangeRates = async () => {
  try {
    const response = await fetch('https://cdn.jsdelivr.net/npm/@fawazahmed0/currency-api@latest/v1/currencies/eur.json')
    const data = await response.json()
    exchangeRates.value = data.eur || {}
    console.log('汇率数据加载成功:', exchangeRates.value)
  } catch (error) {
    console.error('获取汇率数据失败:', error)
    exchangeRates.value = {}
  }
}

// 自动填充汇率
const fillExchangeRate = () => {
  if (dynamicForm.value.currencyCodeTarget && exchangeRates.value) {
    const rate = exchangeRates.value[dynamicForm.value.currencyCodeTarget.toLowerCase()]
    if (rate) {
      dynamicForm.value.huilv = rate
    }
  }
}

// 点击外部关闭下拉菜单
const handleClickOutside = (event) => {
  if (!event.target.closest('.currency-dropdown-container')) {
    showCurrencyDropdown.value = false
  }
}

onMounted(() => {
  document.addEventListener('click', handleClickOutside)
})

onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
})

// 加载状态
const loading = ref({
  areas: false,
  industries: false,
  formParams: false,
  calculating: false
})

async function fetchCountries() {
  loading.value.areas = true
  try {
    const res = await areaApi.getCountries()
    const list = res?.data || res?.rows || []
    countries.value = list.map((c) => ({
      id: c.id,
      name: c.countryNameEn,
      countryCode: c.countryCode,
      currencyCode: c.currencyCode
    }))
  } catch (e) {
    countries.value = []
  } finally {
    loading.value.areas = false
  }
}

async function fetchCurrencySymbol() {
  try {
    const res = await areaApi.getCurrencySymbol()
    const list = res?.data || res?.rows || []
    // 将数组转换为以currencyCode为key的对象
    currencySymbols.value = {}
    list.forEach(currency => {
      currencySymbols.value[currency.currencyCode] = currency.symbol
    })
  } catch (e) {
    console.error('Failed to fetch currency symbol:', e)
    currencySymbols.value = {}
  }
}

// 日期格式化与校验
function padToTwo(n) {
  const s = String(n || '').trim()
  return s.length === 1 ? `0${s}` : s
}

function formatDateToSlash(input) {
  if (!input) return ''
  const raw = String(input).trim().replace(/[.\-]/g, '/').replace(/\s+/g, '')
  // 已经是 YYYY/MM/DD 且合法
  const ymd = raw.split('/')
  if (ymd.length === 3) {
    let [y, m, d] = ymd
    if (/^\d{4}$/.test(y) && /^\d{1,2}$/.test(m) && /^\d{1,2}$/.test(d)) {
      m = padToTwo(m)
      d = padToTwo(d)
      return `${y}/${m}/${d}`
    }
  }
  // 尝试解析连续数字 YYYYMMDD
  if (/^\d{8}$/.test(raw)) {
    const y = raw.slice(0, 4)
    const m = raw.slice(4, 6)
    const d = raw.slice(6, 8)
    return `${y}/${m}/${d}`
  }
  return raw
}

function isValidSlashDate(val) {
  if (!val) return false
  const m = /^([0-9]{4})\/([0-9]{2})\/([0-9]{2})$/.exec(val)
  if (!m) return false
  const year = Number(m[1])
  const month = Number(m[2])
  const day = Number(m[3])
  if (month < 1 || month > 12) return false
  const daysInMonth = new Date(year, month, 0).getDate()
  return day >= 1 && day <= daysInMonth
}


const industries = ref([])
const processType = ref('long')
const processTypeLabel = computed(() => (processType.value === 'long' ? 'Long Process' : 'Short Process'))
const selectedIndustry = ref(null)
const formParams = ref([])
const dynamicForm = ref({})
const currentFlowId = ref(null)

// ==================== Huilv 动态字段逻辑 ====================
// 检测后端是否返回 huilv 字段
const hasBackendHuilv = computed(() => {
  return formParams.value.some(param => param.paramKey === 'huilv')
})

// 获取后端的 huilv 字段配置（取第一个）
const backendHuilvField = computed(() => {
  return formParams.value.find(param => param.paramKey === 'huilv')
})

// 动态获取 huilv 标签
const huilvLabel = computed(() => {
  return backendHuilvField.value?.paramLabel || 'Huilv'
})

// 获取 huilv 的 placeholder
const huilvPlaceholder = computed(() => {
  return `Please enter ${formatPlaceholderText(huilvLabel.value)}`
})
// ==================== End Huilv 动态字段逻辑 ====================

const calcForm = ref({
  sinter: null,
  blast: null,
  converter: null,
  rolling: null,
  carbonPrice: null,
  exchangeRate: null,
  exportVolume: null,
  domesticCost: 0
})

const agree = ref(false)
const resultText = ref('Estimated carbon tariff amount: ¥0.00')
const exceed = ref(false)

// 添加表单验证状态
const formErrors = ref({})
const disclaimerError = ref('')

// 将字符串转换为各单词首字母大写的格式
function toTitleCase(str) {
  if (!str) return ''
  return str.toLowerCase().replace(/\b\w/g, (char) => char.toUpperCase())
}

async function fetchIndustries() {
  loading.value.industries = true
  try {
    const res = await countApi.listIndustry()
		const list = res?.rows || res?.data || []

    industries.value = list.map((x) => ({
      code: x.code || x.industryId || x.id,
      name: toTitleCase(x.name || x.title || x.industryName || ''),
      image: x.image || x.pictureUrl || x.profileUrl || '',
      active: false
    }))
  } catch (e) {
    industries.value = []
  } finally {
    loading.value.industries = false
  }
}

async function fetchFormParams(industryId) {
  loading.value.formParams = true
  try {
    const res = await countApi.getFormParams(industryId)
    if (res.code === 200 && res.data) {
      formParams.value = res.data
      // 初始化动态表单
      dynamicForm.value = {}
      
      // 检查是否有多个flowId
      const flowIds = [...new Set(formParams.value.map(param => param.flowId))]
      
      if (flowIds.length === 1) {
        // 只有一个flowId，初始化所有字段
        currentFlowId.value = flowIds[0]
        formParams.value.forEach(param => {
          dynamicForm.value[param.paramKey] = ''
        })
      } else {
        // 多个flowId，初始化节点字段并选择默认flow
        const nodeFields = formParams.value.filter(param => param.isNode === 'Y')
        
        // 初始化所有节点字段
        nodeFields.forEach(param => {
          dynamicForm.value[param.paramKey] = ''
        })
        
        // 默认选择第一个流程并设置初始值
        if (flowIds.length > 0) {
          const firstFlowId = flowIds[0]
          const firstFlowNodeFields = formParams.value.filter(param => 
            param.flowId === firstFlowId && param.isNode === 'Y'
          )
          
          // 为第一个流程的节点字段设置默认值
          firstFlowNodeFields.forEach(field => {
            if (field.nodeVal) {
              dynamicForm.value[field.paramKey] = field.nodeVal
            }
          })
          
          currentFlowId.value = firstFlowId
        }
      }
      
      // ⚠️ 新增：确保 currencyCodeTarget 和 huilv 始终被初始化
      if (!dynamicForm.value.hasOwnProperty('currencyCodeTarget')) {
        dynamicForm.value.currencyCodeTarget = ''
      }
      
      // 如果后端返回了 huilv 字段，确保它被初始化
      // 注意：不要使用 hasBackendHuilv.value，因为可能存在循环依赖
      const hasHuilv = formParams.value.some(param => param.paramKey === 'huilv')
      if (hasHuilv && !dynamicForm.value.hasOwnProperty('huilv')) {
        dynamicForm.value.huilv = ''
      }
    }
  } catch (e) {
    console.error('Failed to fetch form params:', e)
    formParams.value = []
  } finally {
    loading.value.formParams = false
  }
}

function toggleIndustry(item) {
  if (!item) return
  industries.value = industries.value.map(it => ({ ...it, active: it.code === item.code }))
  selectedIndustry.value = item
  if (item.code) {
    fetchFormParams(item.code)
  }
}

// 监听国家选择变化，自动设置默认货币
watch(() => form.value.country, (newCountry) => {
  console.log('Country changed:', newCountry)
  if (newCountry && countries.value.length > 0) {
    const selectedCountry = countries.value.find(c => c.id === newCountry)
    if (selectedCountry && selectedCountry.currencyCode) {
      // 自动设置为该国家的货币
      dynamicForm.value.currencyCodeTarget = selectedCountry.currencyCode
      // 自动填充汇率
      fillExchangeRate()
    }
  }
})

onMounted(async () => {
  await Promise.all([fetchCountries(), fetchIndustries(), fetchCurrencySymbol(), fetchExchangeRates()])
  if (industries.value.length > 0) {
    toggleIndustry(industries.value[0])
  }
})

async function handleCalculate() {
  // 重置错误状态
  formErrors.value = {}
  disclaimerError.value = ''
  
  if (!selectedIndustry.value) {
    alert('Please select an industry first')
    return
  }
  
  // 规范化日期格式
  form.value.startDate = formatDateToSlash(form.value.startDate)
  form.value.endDate = formatDateToSlash(form.value.endDate)
  
  // 检查基本信息必填字段
  if (!form.value.country) {
    formErrors.value.country = 'Country is required'
  }
  if (!form.value.startDate) {
    formErrors.value.startDate = 'Start date is required'
  } else if (!isValidSlashDate(form.value.startDate)) {
    formErrors.value.startDate = 'Date must be in YYYY/MM/DD'
  }
  if (!form.value.endDate) {
    formErrors.value.endDate = 'End date is required'
  } else if (!isValidSlashDate(form.value.endDate)) {
    formErrors.value.endDate = 'Date must be in YYYY/MM/DD'
  }
  if (!form.value.enterpriseName) {
    formErrors.value.enterpriseName = 'Enterprise Name is required'
  }
  // if (!form.value.contactInformation) {
  //   formErrors.value.contactInformation = 'Contact Information is required'
  // }
  if (!form.value.contactEmail) {
    formErrors.value.contactEmail = 'Contact Email is required'
  }
  
  // 如果都合法，校验开始早于结束
  if (!formErrors.value.startDate && !formErrors.value.endDate) {
    const s = new Date(form.value.startDate.replace(/\//g, '-'))
    const e = new Date(form.value.endDate.replace(/\//g, '-'))
    if (s.getTime() > e.getTime()) {
      formErrors.value.endDate = 'End date must be after start date'
    }
  }
  
  // 检查免责声明
  if (!agree.value) {
    disclaimerError.value = 'You must agree to the disclaimer to continue'
    return
  }
  
  // ⭐ 新增：检查登录状态（在调用 API 之前）
  if (!localStorage.getItem('token')) {
    const { showLoginDialog } = useLoginDialog()
    showLoginDialog('login')
    const { $toast } = useNuxtApp()
    $toast.error('Please login to submit the form')
    return // 停止执行，不调用 API
  }
  
  // 检查动态表单必填字段
  // 检查节点字段
  visibleNodeFields.value.forEach(param => {
    if (!dynamicForm.value[param.paramKey]) {
      formErrors.value[param.paramKey] = `${param.paramLabel} is required`
    }
  })
  
  // 检查当前流程的必填字段
  currentFormFields.value.forEach(param => {
    if (param.isNode === 'Y' && !dynamicForm.value[param.paramKey]) {
      formErrors.value[param.paramKey] = `${param.paramLabel} is required`
    }
  })
  
  // ⚠️ 检查 huilv 字段（使用动态 label）
  if (!dynamicForm.value.huilv) {
    formErrors.value.huilv = `${huilvLabel.value} is required`
  }
  
  // 检查货币代码字段
  if (!dynamicForm.value.currencyCodeTarget) {
    formErrors.value.currencyCodeTarget = 'Currency is required'
  }
  
  // 如果有错误，显示toast提示并不提交
  if (Object.keys(formErrors.value).length > 0) {
    const { $toast } = useNuxtApp()
    const firstError = Object.values(formErrors.value)[0]
    $toast.error(firstError)
    return
  }
  
  // 所有验证都通过，开始loading
  loading.value.calculating = true
  
  try {
    // 获取当前选中的流程ID
    let submitFlowId = currentFlowId.value
    
    // 如果没有设置，尝试从formParams获取第一个flowId
    if (!submitFlowId && formParams.value.length > 0) {
      submitFlowId = formParams.value[0].flowId
    }
    
    if (!submitFlowId) {
      alert('Flow ID not found')
      loading.value.calculating = false
      return
    }
    let currencyCodeTarget = dynamicForm.value.currencyCodeTarget
    delete dynamicForm.value.currencyCodeTarget

    // 准备提交数据
    const submitData = {
      industryId: selectedIndustry.value.code,
      flowId: submitFlowId,
      basicInfo: {
      currencyCodeTarget:currencyCodeTarget,

        countryId: form.value.country,
        startDate: form.value.startDate,
        endDate: form.value.endDate,
        enterpriseName: form.value.enterpriseName,
        contactInformation: form.value.contactInformation,
        contactEmail: form.value.contactEmail
      },
      params: dynamicForm.value
    }
    
    // 调用保存接口（仅在已登录时执行）
    const response = await countApi.saveRecord(submitData)
    if (response.code === 200) {
      console.log('Submitted data:', submitData)
      const { $toast } = useNuxtApp()
      $toast.success('Submitted successfully')
      // 已登录：直接打开结果页
      window.open(`/echart?recordId=${response.data}`, '_blank')
    } else {
      const { $toast } = useNuxtApp()
      $toast.error('Submission failed', response)
    }

  } catch (error) {
    console.error('Submission error:', response)
    const { $toast } = useNuxtApp()
    $toast.error('Submission error',response)
  } finally {
    loading.value.calculating = false
  }
}

// 格式化placeholder文本的工具函数
function formatPlaceholderText(label) {
  if (!label) return ''

  // 特殊术语映射表
  const specialTerms = {
    'Huilv': 'huilv',
    'CO2': 'CO2',
    'EU': 'EU',
    'USD': 'USD',
    'EUR': 'EUR',
    'CNY': 'CNY',
    'GBP': 'GBP',
    'JPY': 'JPY'
  }

  // 检查特殊术语
  if (specialTerms.hasOwnProperty(label)) {
    return specialTerms[label]
  }

  // 处理复合词（空格分隔或斜杠分隔）
  if (label.includes(' ') || label.includes('/')) {
    return label.toLowerCase()
  }

  // 一般情况：首字母小写
  return label.charAt(0).toLowerCase() + label.slice(1)
}

// 格式化化学公式显示
function formatChemicalFormula(text) {
  if (!text) return text

  // 化学公式映射表
  const chemicalFormulas = [
    { pattern: /CO2/g, replacement: 'CO₂' },
    { pattern: /H2O/g, replacement: 'H₂O' },
    { pattern: /SO2/g, replacement: 'SO₂' },
    { pattern: /NO2/g, replacement: 'NO₂' },
    { pattern: /CH4/g, replacement: 'CH₄' },
    { pattern: /N2O/g, replacement: 'N₂O' }
  ]

  let result = text
  chemicalFormulas.forEach(formula => {
    result = result.replace(formula.pattern, formula.replacement)
  })

  return result
}

// 单位枚举
const UNIT_ENUM = {
  1: 'kgCO₂/t',
  2: 'kgCO₂/t',
  3: '{currency}',
  4: '{currency}',
  5: '{currency}',
  6: '{currency}'
}

function getUnitByParamKey(paramKey) {
  
  // 从当前表单字段中查找对应的fieldUnit
  const field = currentFormFields.value.find(param => param.paramKey === paramKey)
  
  // 如果字段有fieldUnit，通过枚举映射获取单位文本
  if (field?.fieldUnit) {
    const unitId = parseInt(field.fieldUnit)
    const unitText = UNIT_ENUM[unitId] || field.fieldUnit
    
    // 特殊字段：exports（不区分大小写）返回 t（吨）
    if (field.paramLabel?.toLowerCase() === 'exports') {
      return 't'
    }
    // 如果单位包含货币符号占位符，替换为实际选择的货币符号
    if (unitText.includes('{currency}')) {
      const selectedCurrency = dynamicForm.value.currencyCodeTarget
      const currencySymbol = currencySymbols.value[selectedCurrency] || '€'
      const formattedText = unitText.replace('{currency}', currencySymbol)
      return formatChemicalFormula(formattedText)
    }

    return formatChemicalFormula(unitText)
  }
  
  return ''
}

function getCurrencySymbolUnit() {
  // 根据选中的国家获取对应的货币符号
  if (form.value.country && countries.value.length > 0) {
    const selectedCountry = countries.value.find(c => c.id === form.value.country)
    if (selectedCountry && selectedCountry.currencyCode && currencySymbols.value[selectedCountry.currencyCode]) {
      const currencySymbol = currencySymbols.value[selectedCountry.currencyCode]
      return `${currencySymbol}` // 返回格式：货币符号/€
    }
  }
  // /€
  return '¥/€' // 默认单位
}

function parseParamJson(jsonString) {
  if (!jsonString) return []
  try {
    return JSON.parse(jsonString)
  } catch (e) {
    console.error('Failed to parse paramJson:', e)
    return []
  }
}

// 钢铁行业特殊处理函数
function getSteelIndustryFlowId() {
  console.log('Steel industry special processing')
  
  const currentSelections = {}
  
  // 收集所有节点字段的当前选择
  const nodeFieldKeys = [...new Set(formParams.value
    .filter(param => param.isNode === 'Y')
    .map(param => param.paramKey)
  )]
  
  nodeFieldKeys.forEach(paramKey => {
    const selectedValue = dynamicForm.value[paramKey]
    if (selectedValue) {
      currentSelections[paramKey] = selectedValue
    }
  })
  
  console.log('Steel currentSelections:', currentSelections)
  
  // 获取所有可能的flowId
  const flowIds = [...new Set(formParams.value.map(param => param.flowId))]
  
  for (const flowId of flowIds) {
    // 获取该flowId的所有节点字段
    const nodeFields = formParams.value.filter(param => 
      param.flowId === flowId && param.isNode === 'Y'
    )
    
    console.log(`Checking steel flowId ${flowId}, nodeFields:`, nodeFields)
    
    // 检查是否所有nodeVal都匹配当前选择
    let allMatch = true
    
    for (const field of nodeFields) {
      if (field.nodeVal) {
        const currentValue = currentSelections[field.paramKey]
        console.log(`Checking ${field.paramKey}: current=${currentValue}, nodeVal=${field.nodeVal}`)
        if (currentValue !== field.nodeVal) {
          allMatch = false
          break
        }
      }
    }
    
    if (allMatch && nodeFields.length > 0) {
      console.log('Found steel flowId by nodeVal:', flowId)
      return flowId
    }
  }
  
  console.log('No matching steel flowId found')
  return null
}

// 根据当前所有节点字段的值获取对应的flowId
function getCurrentFlowId() {
  console.log('getCurrentFlowId called')
  console.log('dynamicForm.value:', dynamicForm.value)
  
  // 获取所有flowId
  const flowIds = [...new Set(formParams.value.map(param => param.flowId))]
  
  // 遍历每个flowId，找到完全匹配当前选择的那个
  for (const flowId of flowIds) {
    const nodeFields = formParams.value.filter(param => 
      param.flowId === flowId && param.isNode === 'Y'
    )
    
    console.log(`Checking flowId ${flowId}, nodeFields:`, nodeFields)
    
    // 检查是否所有节点字段都匹配
    let allMatch = true
    
    for (const field of nodeFields) {
      const currentValue = dynamicForm.value[field.paramKey]
      
      // 如果当前字段有值，检查是否与nodeVal匹配
      if (currentValue && field.nodeVal) {
        if (currentValue !== field.nodeVal) {
          allMatch = false
          break
        }
      } else if (field.nodeVal) {
        // 如果字段没有值但nodeVal有值，不匹配
        allMatch = false
        break
      }
    }
    
    if (allMatch && nodeFields.length > 0) {
      console.log('Found matching flowId:', flowId)
      return flowId
    }
  }
  
  console.log('No matching flowId found, returning first flowId')
  return flowIds[0] || null
}

// 检查是否所有flowId都一致
const hasMultipleFlows = computed(() => {
  const flowIds = [...new Set(formParams.value.map(param => param.flowId))]
  return flowIds.length > 1
})

// 获取节点字段（isNode === 'Y'），按层级排序
const nodeFields = computed(() => {
  if (!hasMultipleFlows.value) return [] // 如果只有一个flowId，不显示节点字段
  
  const seen = new Set()
  const fields = formParams.value.filter(param => {
    if (param.isNode === 'Y' && !seen.has(param.paramKey)) {
      seen.add(param.paramKey)
      return true
    }
    return false
  })
  
  // 按parentId排序，没有parentId的在前面
  return fields.sort((a, b) => {
    if (!a.parentId && b.parentId) return -1
    if (a.parentId && !b.parentId) return 1
    return 0
  })
})

// 钢铁行业节点字段特殊处理
function getSteelVisibleNodeFields() {
  const result = []
  const fieldMap = new Map()
  
  // 收集所有节点字段并去重
  for (const field of formParams.value) {
    if (field.isNode === 'Y') {
      if (!fieldMap.has(field.paramKey)) {
        const allOptions = new Set()
        
        formParams.value.forEach(param => {
          if (param.paramKey === field.paramKey && param.isNode === 'Y') {
            const options = parseParamJson(param.paramJson)
            options.forEach(opt => allOptions.add(JSON.stringify(opt)))
          }
        })
        
        const uniqueOptions = Array.from(allOptions).map(opt => JSON.parse(opt))
        
        fieldMap.set(field.paramKey, {
          ...field,
          paramJson: JSON.stringify(uniqueOptions)
        })
      }
    }
  }
  
  // 按层级排序：没有parentId的在前，有parentId的在后
  const allFields = Array.from(fieldMap.values())
  const firstLevelFields = allFields.filter(field => !field.parentId)
  const secondLevelFields = allFields.filter(field => field.parentId)
  
  // 添加第一级字段
  result.push(...firstLevelFields)
  
  // 添加第二级字段，检查依赖关系
  for (const field of secondLevelFields) {
    if (field.parentVal) {
      // 检查父级字段的选择是否匹配
      const parentKey = getParentKeyByParentId(field.parentId)
      const parentValue = dynamicForm.value[parentKey]
      if (parentValue === field.parentVal) {
        result.push(field)
      }
    } else {
      result.push(field)
    }
  }
  
  return result
}

// 获取当前可见的节点字段（考虑依赖关系）
const visibleNodeFields = computed(() => {
  // 如果只有一个流程，不显示节点字段
  if (!hasMultipleFlows.value) return []
  
  // 获取去重的节点字段，合并所有选项
  const fieldMap = new Map()
  
  for (const field of formParams.value) {
    if (field.isNode === 'Y') {
      if (!fieldMap.has(field.paramKey)) {
        // 创建新的字段，合并所有可能的选项
        const allOptions = new Set()
        
        // 收集所有相同paramKey的选项
        formParams.value.forEach(param => {
          if (param.paramKey === field.paramKey && param.isNode === 'Y') {
            const options = parseParamJson(param.paramJson)
            options.forEach(opt => allOptions.add(JSON.stringify(opt)))
          }
        })
        
        // 转换回对象数组并去重
        const uniqueOptions = Array.from(allOptions).map(opt => JSON.parse(opt))
        
        fieldMap.set(field.paramKey, {
          ...field,
          paramJson: JSON.stringify(uniqueOptions)
        })
      }
    }
  }
  
  // 处理依赖关系 - 只显示符合当前选择的字段
  const result = []
  const fields = Array.from(fieldMap.values())
  
  for (const field of fields) {
    // 如果字段没有父级依赖，直接显示
    if (!field.parentId) {
      result.push(field)
    } else {
      // 如果有父级依赖，检查是否满足条件
      if (field.parentVal) {
        // 找到父级字段
        const parentField = fields.find(f => !f.parentId) // 简化：假设父级字段没有parentId
        if (parentField) {
          const parentValue = dynamicForm.value[parentField.paramKey]
          if (parentValue === field.parentVal) {
            result.push(field)
          }
        }
      }
    }
  }
  
  return result
})

// 根据parentId获取对应的paramKey
function getParentKeyByParentId(parentId) {
  // 在这个数据结构中，parentId似乎对应某个字段的ID
  // 根据数据，parentId: 22 对应的是 "生产工艺" 字段
  // 这里需要根据实际的映射关系来处理
  return 'shengchangongyi' // 暂时硬编码，实际应该动态获取
}

// 获取当前流程的表单字段，去重相同的paramKey
const currentFormFields = computed(() => {
  console.log('currentFormFields computed')
  console.log('hasMultipleFlows:', hasMultipleFlows.value)
  console.log('currentFlowId:', currentFlowId.value)
  
  const seen = new Set()
  
  // 如果只有一个flowId，显示所有非节点字段
  if (!hasMultipleFlows.value) {
    const result = formParams.value.filter(param => {
      // ⚠️ 移除了 param.paramKey !== 'huilv' 条件，允许 huilv 进入字段列表
      if (param.isNode !== 'Y' && !seen.has(param.paramKey)) {
        seen.add(param.paramKey)
        return true
      }
      return false
    })
    console.log('Single flow result:', result)
    return result
  }
  
  // 如果有多个flowId，按当前选择的flowId过滤
  if (!currentFlowId.value) {
    console.log('No currentFlowId, returning empty array')
    return []
  }
  
  const result = formParams.value.filter(param => {
    if (param.flowId === currentFlowId.value && param.isNode !== 'Y' && !seen.has(param.paramKey)) {
      seen.add(param.paramKey)
      return true
    }
    return false
  })
  
  console.log('Multiple flow result:', result)
  return result
})

// 排除 huilv 的字段列表（用于动态字段循环渲染）
const currentFormFieldsWithoutHuilv = computed(() => {
  return currentFormFields.value.filter(param => param.paramKey !== 'huilv')
})

// 监听节点字段变化，更新当前流程
function onNodeFieldChange(paramKey, value) {
  console.log('onNodeFieldChange called:', paramKey, value)
  
  // 先设置值
  dynamicForm.value[paramKey] = value
  
  // 如果是第一级字段（生产工艺），需要清空第二级字段
  if (paramKey === 'shengchangongyi') {
    // 清空钢铁类型字段
    if (dynamicForm.value['gangtieleixing']) {
      dynamicForm.value['gangtieleixing'] = ''
    }
    
    // 如果选择了短流程，自动设置第一个钢铁类型
    if (value === 'dlc') {
      const steelTypeField = formParams.value.find(param => 
        param.paramKey === 'gangtieleixing' && param.parentVal === 'dlc'
      )
      if (steelTypeField) {
        const options = parseParamJson(steelTypeField.paramJson)
        if (options.length > 0) {
          dynamicForm.value['gangtieleixing'] = options[0].value
        }
      }
    }
  }
  
  // 重新计算当前flowId
  const newFlowId = getCurrentFlowId()
  console.log('New flowId:', newFlowId)
  currentFlowId.value = newFlowId
  
  // 清空当前流程的非节点表单数据
  const fieldsToReset = currentFormFields.value
  fieldsToReset.forEach(field => {
    if (field.isNode !== 'Y') {
      dynamicForm.value[field.paramKey] = ''
    }
  })
}
</script>

<style>
.bg-blue-700{
	background-color: #0066a1;
}
</style>


